package com.sghj.utils;


import com.sghj.config.handler.ResultCode;
import com.sghj.config.handler.exceptionHandler.MyException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author helen
 * @since 2019/10/16
 */
@Component
public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 4;

    public static final long MILLIS_MINUTE_TEN = 1000 * 60 * 10;        //最低有效期
    //public static final long EXPIRE = 1000 * 30;
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    public static String getJwtToken(Integer id, String nickname){

        //Date expTime=new Date(System.currentTimeMillis() + EXPIRE);

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(new Date())
                //.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //.setExpiration(expTime)         //设置过期时间
                .claim("id", id)
                .claim("nickname", nickname)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            throw new MyException(ResultCode.FAIL,"token无效");
        }
        return true;
    }

    /**
     * 根据token获取id
     * @param jwtToken
     * @return
     */
    public static Integer getIdByToken(String jwtToken){
        if (StringUtils.isEmpty(jwtToken)){
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (Integer) claims.get("id");
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            //String jwtToken = request.getHeader("Authorization");
            String jwtToken = getToken(request);
            if(StringUtils.isEmpty(jwtToken)||jwtToken==null) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据request请求获取当前用户id
     * @param request
     * @return
     */
    public static Integer getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = getToken(request);
        if(StringUtils.isEmpty(jwtToken)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (Integer) claims.get("id");
    }

    public static String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies ==null){
            throw new MyException(ResultCode.NoCookies,"登录超时，请重新登录");
        }
        for (Cookie c : cookies) {
            if (c.getName().equals("token")) {
                return c.getValue();
            }
        }
        return null;
    }

    /**
     * 获取后台管理端token
     * @param request
     * @return
     */
    public String getManageToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies ==null){
            throw new MyException(ResultCode.NoCookies,"登录超时，请重新登录");
        }
        for (Cookie c : cookies) {
            if (c.getName().equals("zjcq_token")) {
                return c.getValue();
            }
        }
        return null;
    }

    /**
     * 更新token有效期
     * @param request
     */
    public void verifyToken(HttpServletRequest request) {

    }
}
